import axios from "axios";
import {ElMessage} from "element-plus";


// console.log('process.env.NODE_ENV', process.env.NODE_ENV);
// export const BASE_URL = process.env.NODE_ENV === 'development' ? '/api' : '/';
export const BASE_URL = process.env.NODE_ENV === 'development' ? '/api' : '/';

axios.defaults.withCredentials = true;

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 60000,
  withCredentials: true
})

instance.interceptors.request.use(config => {
  config.headers = {
    'Content-Type': 'application/json',
  }
  if (sessionStorage.getItem("username")) {
    config.headers.username = sessionStorage.getItem("username") || '';
  }
  if (sessionStorage.getItem("token")) {
    config.headers.token = sessionStorage.getItem("token") || '';
  }
  return config
}, error => {
  return Promise.reject(error);
})

instance.interceptors.response.use(response => {
  const {body, code, msg, success, time} = response.data;
  if (success) {
    return body as any;
  } else if (code === 902) {
    sessionStorage.setItem("token", "");
    sessionStorage.setItem("username", "");
    sessionStorage.setItem("isLogin", "fail");
    ElMessage({
      message: body,
      type: 'warning',
    });
    setTimeout(() => {
      location.reload();
    }, 1000);
  } else {
    return Promise.reject(new Error(body));
  }
  const returnObj = {
    msg: msg,
    data: body
  } as any;
  return returnObj;
}, error => {
  console.log('error', error);
  return Promise.reject(error);
})

export const fetch_post = instance.post as any as (...arg: Parameters<typeof instance.post>) => Promise<any>;

export const fetch_get = instance.get as any as (...arg: Parameters<typeof instance.get>) => Promise<any>;
